<script lang="ts" setup>
import { createCardAPI, getCardDetailAPI, renewCardAPI, updateCardAPI } from '@/apis/card';
import type { CardDetail, CardParams } from '@/types/card';
import { dayjs, ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';



// 1. 添加月卡
// 车辆信息表单
const carInfoForm = ref<Partial<CardParams>>({
  personName: '', // 车主姓名
  phoneNumber: '', // 联系方式
  carNumber: '', // 车牌号码
  carBrand: '' // 车辆品牌
})

const carInfoFormRules = ref<FormRules<CardParams>>({
  personName: [
    { required: true, message: '请输入车主姓名', trigger: 'blur'  }
  ],
  phoneNumber: [
    { required: true, message: '请输入联系方式', trigger: 'blur'  },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'  }
  ],
  carNumber: [
    { required: true, message: '请输入车牌号码', trigger: 'blur'  },
    { pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/, message: '请输入正确的车牌号码', trigger: 'blur'  }
  ],
  carBrand: [
    { required: true, message: '请输入车辆品牌', trigger: 'blur'  }
  ]
})

// 表单2 - 缴费信息
const feeForm = ref<Partial<CardParams>>({
  cardStartDate: '',
  cardEndDate: '',
  paymentAmount: '',
  paymentMethod: 'Alipay'
})

const feeFormRules = ref<FormRules<CardParams>>({
  cardEndDate: [
    { required: true, message: '请选择有效日期', trigger: 'blur'  }
  ],
  paymentAmount: [
    { required: true, message: '请输入金额', trigger: 'blur'  }
  ],
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'blur'  }
  ]
})
// 支付方式列表
const payMethodList = [
  { id: 'Alipay', name: '支付宝' },
  { id: 'WeChat', name: '微信' },
  { id: 'Cash', name: '线下' }
]
// 日期数组
const cardDateArr = ref<string[]>([])
// 监听日期变化，收集后端所需的数据
watch(cardDateArr, (val) => {
  if (val) {
    feeForm.value.cardStartDate = val[0]
    feeForm.value.cardEndDate = val[1]
  } else {
    feeForm.value.cardStartDate = ''
    feeForm.value.cardEndDate = ''
  }
}, { deep: true })

// 获取两个表单实例，用于整个表单校验
const carInfoFormRef = ref<FormInstance>()
const feeFormRef = ref<FormInstance>()

const router = useRouter()
  // 点击确定，提交表单
  const onSubmit = async () => {
     try{
        // await 等待两个表单校验
        await Promise.all([
          carInfoFormRef.value?.validate(),  // 表单1 整体校验
          feeFormRef.value?.validate()  // 表单2 整体校验
        ])
      
        // 调用接口，把数据提交给后端
      // 判断是否有 id，实现 编辑 或 添加
      if(route.params.id) {
        // 有 id 是编辑月卡
        await updateCardAPI({
          ...carInfoForm.value,
          ...feeForm.value,
          ...editForm.value
        })
      } else if(route.query.id) {
        console.log('1',carInfoForm.value)
        console.log('2',feeForm.value)
        console.log('3',editForm.value)
        await renewCardAPI({
          ...feeForm.value,
          carInfoId: editForm.value.carInfoId
        })

      }else    
      {
        // 无 id 才是添加月卡
        await createCardAPI({
          ...carInfoForm.value,
          ...feeForm.value
        })
      }
      // 轻提示
      ElMessage.success(route.params.id ? '编辑成功' : '添加成功')
        router.back()

     } catch {}
  }
// 3. 重置表单
const onReset = () => {
  // resetFields()	将值重置为初始值，并移除校验结果
  feeFormRef.value?.resetFields()
  carInfoFormRef.value?.resetFields()
  // 清空特殊的日期数组
  cardDateArr.value = []
}

// 表单3: 编辑时，保存所需的两个 id（看不到的表单）
const editForm = ref<Partial<CardDetail>>({
  carInfoId: undefined,
  rechargeId: undefined
})

const route = useRoute()
// 获取月卡详情 编辑回显
const getDetailData = async (id : string) => {
  // 根据 id 获取月卡详情
  const res = await getCardDetailAPI(id)
  // 提取表单所需的数据，提取所有数据，分配到三个表单中
  const { personName, phoneNumber, carNumber, carBrand, cardStartDate, cardEndDate, paymentAmount,paymentMethod, carInfoId, rechargeId } = res.data
  // 绑定到表单1 回显
  carInfoForm.value = { personName, phoneNumber, carNumber, carBrand }
  // 绑定到表单2 回显
  feeForm.value = { cardStartDate, cardEndDate, paymentAmount, paymentMethod }
  // 单独处理日期 picker 数据（前后端数据不一致，特殊情况特殊处理）
  cardDateArr.value = [cardStartDate, cardEndDate]
  // 绑定到表单3，编辑时，所需的两个 id（看不到的表单）
  editForm.value = { carInfoId, rechargeId }
}
// 获取月卡详情 编辑回显
const getDetailDataRenew = async (id : string) => {
  // 根据 id 获取月卡详情
  const res = await getCardDetailAPI(id)
  // 提取表单所需的数据，提取所有数据，分配到三个表单中
  const { personName, phoneNumber, carNumber, carBrand, cardStartDate, cardEndDate, paymentAmount,paymentMethod, carInfoId, rechargeId } = res.data
  // 绑定到表单1 回显
  carInfoForm.value = { personName, phoneNumber, carNumber, carBrand }
  const cardEndDate2 = dayjs(dayjs(cardEndDate).valueOf() + 24 * 60 * 60 * 1000).format('YYYY-MM-DD')
  // console.log('cardEndDate2',cardEndDate2)
  // 绑定到表单2 回显
  feeForm.value = { 
    cardStartDate: cardEndDate2, 
    cardEndDate: '', 
    paymentAmount, 
    paymentMethod 
  }
  // 单独处理日期 picker 数据（前后端数据不一致，特殊情况特殊处理）
  // cardDateArr.value = [cardStartDate, cardEndDate]
  // 绑定到表单3，编辑时，所需的两个 id（看不到的表单）
  editForm.value = { carInfoId, rechargeId }
}
const renewDisableDate = (time: Date) => {
  // 将rentForm.value.startTime转回时间戳
  const startTime = dayjs(feeForm.value.cardStartDate).valueOf()
  // 禁用日期的范围 是上个合同的日期+1天
  return time.getTime() < startTime + 8.64e7
}


if(route.params.id) {
  getDetailData(route.params.id as string)
}

//*********** 续费月卡 ***********
if(route.query.id){
  console.log('id', route.query.id)
  getDetailDataRenew(route.query.id as string)
}


</script>

<template>
  <div class="add-card">
    <header class="add-header">
      <el-page-header :content="$route.params.id? '编辑月卡' : $route.query.id ? '续费月卡' : '增加月卡' " @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">车辆信息</div>
        <div class="form">
          {{ carInfoForm }}
          <el-form ref="carInfoFormRef" label-width="100px" :model="carInfoForm" :rules="carInfoFormRules">
            <el-form-item label="车主姓名" prop="personName">
              <el-input v-model="carInfoForm.personName" :disabled="$route.query.id ? true : false" />
            </el-form-item>
            <el-form-item label="联系方式" prop="phoneNumber">
              <el-input v-model="carInfoForm.phoneNumber" :disabled="$route.query.id ? true : false" />
            </el-form-item>
            <el-form-item label="车辆号码" prop="carNumber">
              <el-input v-model="carInfoForm.carNumber" :disabled="$route.query.id ? true : false" />
            </el-form-item>
            <el-form-item label="车辆品牌" prop="carBrand">
              <el-input v-model="carInfoForm.carBrand" :disabled="$route.query.id ? true : false" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="form-container">
        <div class="title">最新一次月卡缴费信息</div>
        <div class="form">
          {{ feeForm }}
          <el-form ref="feeFormRef" label-width="100px" :model="feeForm" :rules="feeFormRules">
            <el-form-item label="有效日期" prop="cardEndDate">
              <div v-if="$route.query.id ? true : false">
                <el-input disabled v-model="feeForm.cardStartDate" placeholder="开始日期" style="width: 200px;" />
                至
                <el-date-picker type="date" :disabled-date="renewDisableDate" v-model="feeForm.cardEndDate" format="YYYY-MM-DD" clearable></el-date-picker>
              </div>
              <div v-else>
                <el-date-picker 
              
              v-model="cardDateArr"
              value-format="YYYY-MM-DD" 
              type="daterange" 
              range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" 
              />
              </div>
              
            </el-form-item>
            <el-form-item label="支付金额" prop="paymentAmount">
              <el-input v-model="feeForm.paymentAmount" />
            </el-form-item>
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="feeForm.paymentMethod">
                <el-option v-for="item in payMethodList" :key="item.id" :value="item.id" :label="item.name" />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>

    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="onReset" v-if="!$route.query.id">重置</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<style scoped lang="scss">
.add-card {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }

    .preview {
      img {
        width: 100px;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>